<?php
/** 
 * @package AMFramework
 * @subpackage Data
 * @author Marcu Alexandru
 * @version 1.0 $Build 305b  
 */
defined('_INDEX') or die('Restricted');

/**
 
 Router[]
a)General pentru toate aplicatiile foloseste o singura schema ce este definita in config
	ex: ~app/~controller/~task/~format/~module	
	- Nu permite alte variabile pentru get (care vor fi tot in URI)
b)Specificat de aplicatie (Route Mappings) prin XML
	- Construirea rutelor din linkuri (Route Create)
	- Parsingul rutelor din linkuri create de aplicatie (Route Parse)
		Clasa da parsing si clasa de creare sunt in librarii, regulile pentru create si parse 
		se vor citi din XML
 
 
 * Dependente - Config, fwAutoload
 * @author Marcu
 *
 */
class Amfw_Router {
	protected static $command;
	protected static $tokens;
	protected static $enabled;
	
	public static function fetchRoutingCnf() {
		global $framework;
		$routing = $framework->getConfig('routing');
		$enabled = ($routing['enabled'] == "yes") ? true : false;
		if($enabled) { self::$tokens = $routing['tokens']; }
		self::$enabled = $enabled;
	}
	
	public static function fetchTokens() {
		global $framework;
		$routing = $framework->getConfig('routing');
		$command = self::$command;
		$tmp=current($command);
		$app = Amfw_Application::_();
		if(!isset($app)) {
			return; // Functia trebuie chemata dupa ce a fost initializata aplicatia
		}
		//Daca avem aplicatia pe prima pozitie, o scoatem din calcul
		if(strtolower($tmp)==strtolower($app->name)) {
			reset($command);
			array_shift($command);
		}
		//var_dump($routing['tokens']);
		$tokens = array();
		foreach($routing['tokens'] as $token) {
			$tmp = array_keys($token);
			$tmp = (String) array_shift($tmp);
			// Default value, in case we actually need it
			$def = array_values($token);
			$def = (String) array_shift($def);
			
			if(current($command)) {
				$tokens[$tmp] =  current($command);
				next($command);
			}elseif(!empty($def)) { //If we don't have anything in the command we start using default values;
				$tokens[$tmp] = $def;  
			}else {
				return;//We're giving up..
			}
		}
		self::$tokens = $tokens;
	}
	
	public static function createRequest() {
		$tokens = self::$tokens;
		if(!isset($tokens)) {
			return; // fetchTokens trebuie chemat inainte
		}
		//var_dump($tokens);
		foreach($tokens as $var => $value) {
			Amfw_Request::setv($var,$value,'GET');
		}
	}
	
	public static function enabled() { return self::$enabled; }
	public static function tokens() { return self::$tokens; }
	public static function command() { return self::$command; }
	
	public static function fetchUriCommand() {
		// Solves the URL splitting it in an array of tokens used as command
		$basepath = str_replace('\\','/',BASE_PATH);
		$basepath = explode('/',$basepath);

		// Removes the base URI from the actual URL (useful when the application is hosted under a sub-domain)
		$request_uri = explode('/',$_SERVER['REQUEST_URI']);
		$request_uri = array_diff($request_uri,array_intersect($basepath,$request_uri));
		
		// Gets the name of the script, (i.e. index.php) just to make sure it`s not among the tokens
		$script_name = @end(explode('/',$_SERVER['SCRIPT_NAME']));
		
		// Trims the Uri item and removes it if: (a) it matches the script name
		// (b) is empty (c) it`s not alphanumeric (with underscore allowed) 
		// avoids having the command mixed with a uri request
		foreach($request_uri as $key => &$value) {
			$request_uri[$key] = trim($value);
			if($value == $script_name || empty($value) || preg_match('/\W+/',$value)) 
				unset($request_uri[$key]);
		}

		unset($value);
		self::$command = $request_uri;
	}
	
	
	
/*	public static function routeApplication() {
		// House rules:
		
		//Pentru aplicatii cu alt id decat 0 (trecuta prima in xml)
		// trebuie intotdeauna specificata aplicatia in URI
		// functia isi da seama daca a fost specificata sau nu o aplicatie
		
		// Pentru aplicatia cu id-ul 0 nu trebuie specificat nicioda URI de aplicatie (se duce in controller)
		// si functia asta nu se activeaza
		
		// TODO: Router implicit pentru aplicatii cu id diferit de 0
		
		//echo 'here';
		// Solves the url splitting it in an array of tokens used as command
		$basepath = str_replace('\\','/',BASE_PATH);
		$basepath = explode('/',$basepath);

		// Removes the base URI from the actual URL (useful when the application is hosted under a sub-domain)
		$request_uri = explode('/',$_SERVER['REQUEST_URI']);
		$request_uri = array_diff($request_uri,array_intersect($basepath,$request_uri));
		
		// Gets the name of the script, (i.e. index.php) just to make sure it`s not among the tokens
		$script_name = @end(explode('/',$_SERVER['SCRIPT_NAME']));
		
		// Removes the name of the script and empty tokens from the URI 
		foreach($request_uri as $key => &$value) {
			$request_uri[$key] = trim($value);
			if($value == $script_name || empty($value)) 
				unset($request_uri[$key]);
		}
		$possibleApp = array_shift($request_uri); // Gets the first command token
		
		global $framework;
		$apps = $framework->getConfig('apps');
		array_shift($apps); // Removing the first application (we don`t need to route the first application)
		foreach($apps as $app) {
			if($app->name == $possibleApp) {
				//var_dump($possibleApp);
				Amfw_Request::setv('application',$possibleApp);
				return;
			}
		}
		


	}*/
	public static function route($url) { return $url; } //Dezactivez temporar routingul
/*	public static function route2($url) {
		$url = substr($url, strrpos($url,'?') + 1);
		$url = explode('&',$url);
		$tokenArray = array();
		foreach($url as $token) {
			$token = explode('=',$token);
			$tokenArray[$token[0]] = $token[1];
		}
		$url = self::_tokensMapping($tokenArray);
		return $url;
	}
	
	private static function _tokensMapping($tokenArray) {
		$url = Amfw_URI::root();
		$url .= isset($tokenArray['application'])? $tokenArray['application'].'/' : '';
		$url .= isset($tokenArray['controller'])? $tokenArray['controller'].'/' : '';
		$url .= isset($tokenArray['task']) 		? $tokenArray['task'].'/' 		: '';
		$url .=	isset($tokenArray['format']) 	? $tokenArray['format'].'/' 	: '';

		return $url;
	}
	public function dispatch() { }	*/
}